<template>
  <div>
<h3 class="title">服务器管理</h3>
    <!--    设置overflow: hidden以解决高度塌陷-->
    <div style="overflow: hidden">
      <!--      排序,增删改查-->
      <el-button type="primary" style="float: right" class="el-icon-download" size="small" @click="serverInfoExport">导出</el-button>

      <el-select v-model="value4" clearable placeholder="请选择服务器">
        <el-option
            v-for="item in serverOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" class="el-icon-search" size="small" style="margin-left: 10px" @click="searchServer">查询</el-button>
      <el-button type="primary" class="el-icon-circle-plus-outline" size="small" @click="addServer">新增</el-button>
      <el-button type="primary" class="el-icon-refresh" size="small" @click="showAll">展示全部数据</el-button>
    </div>
    <title-componet name="服务器信息列表" v-if="this.$store.state.titleState"></title-componet>
    <!-- 修改style，表中数据加粗 2023/1/3-->
    <el-table
        class="InfoData"
        :data="serverData"
        :header-cell-style="this.$handleheader"
        :row-style="this.$rowstyle"
        :cell-style="this.$cellstyle"
        border
    >
      <!--      加个序号，多选框-->
<!--      <el-table-column-->
<!--          type="selection"-->
<!--          width="55">-->
<!--      </el-table-column>-->
      <!-- header-align="center"为新增的居中语句 2023/1/3-->
      <el-table-column
          prop="id"
          label="编号"
          width="80"
          sortable
          header-align="center"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="server_name"
          label="服务器名称"
          header-align="center"
      />
      <el-table-column
          prop="server_mac"
          label="服务器MAC"
          width="320"
          header-align="center"
      >
      </el-table-column>
      <el-table-column
          prop="server_ip"
          label="服务器ip"
          width="220"
          header-align="center"
      >
      </el-table-column>
      <el-table-column
          prop="time"
          label="创建时间"
          width="220"
          sortable
      >
      </el-table-column>
      <el-table-column
          label="操作"
          header-align="center"
          align='center'
      >
        <template slot-scope="scope">
          <el-button type="text" @click="editServer(scope.row)">修改</el-button>
          <el-button type="text" @click="delServer(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    <el-pagination-->
<!--        style="margin-left: 30px;  margin-top: 10px; text-align: right"-->
<!--        background-->
<!--        layout="total, prev, pager, next"-->
<!--        :current-page="currentPage"-->
<!--        :page-size="pageSize"-->
<!--        :total="total"-->
<!--        @current-change="handleCurrentChange">-->
<!--    </el-pagination>-->
    <page :current-page="currentPage" :page-size="pageSize" :total="total" @handleChange="handleCurrentChange"></page>
    <el-dialog
        :title="serverMode"
        :visible.sync="serverDialog"
        width="30%"
        :close-on-click-modal=false
        :show-close=false>
      <el-form ref="serveForm" :rules="rules" :model="serveForm" label-width="120px">
        <el-form-item label="服务器名称" prop="server_name">
          <el-input v-model="serveForm.server_name"></el-input>
        </el-form-item>
        <el-form-item label="服务器MAC" prop="server_mac">
          <el-input v-model="serveForm.server_mac"></el-input>
        </el-form-item>
        <el-form-item label="服务器IP地址" prop="server_ip">
          <el-input v-model="serveForm.server_ip"></el-input>
        </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="serverDialog = false">取 消</el-button>
    <el-button type="primary" @click="addOrEditInfo('serveForm')">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
        title="导出信息填写"
        :visible.sync="exportVisible"
        width="30%"
        :show-close="false"
        :close-on-click-modal="false">

      <el-form ref="form" :model="exportForm" label-width="80px" inline :rules="exportRules">
        <el-form-item label="文件名" prop="name">
          <el-input v-model="exportForm.name"></el-input>
        </el-form-item>
<!--        <el-form-item label="高度" prop="height">-->
<!--          <el-input v-model="exportForm.height"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="宽度" prop="width">-->
<!--          <el-input v-model="exportForm.width"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
<!--      <span style="color: red">*高度建议不超过500，宽度不超过1000</span>-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="exportVisible = false">取 消</el-button>
    <el-button type="primary" @click="startExport('serverInfo',serverData,'serverData'),exportVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import Page from "@/components/page";
import TitleComponet from "@/components/titleComponet";
import ExportDialogComponent from "@/components/exportDialogComponent";
import {exportMixin} from "../components/mixin";
import {addServer, delServer, editServer, searchServer, serverList} from "@/api/server";
import moment from "moment";
// 封装antv的图表导出Url
export default {
  name: "serverInfo",
  components: {ExportDialogComponent, TitleComponet, Page},
  mixins : [exportMixin],
  data() {
    return{
      currentPage:1,
      pageSize:10,
      total:'',
      serverData: null,
      value4:this.$store.state.server.serverId,
      serverOptions:[],
      serverDialog:false,
      serverMode:'',
      serveForm:{
        server_name:'',
        server_mac:'',
        server_ip:'',
        time:''
      },
      rules: {
        server_name: [
          {required: true, message: '请输入服务器名称', trigger: 'blur'},
        ],
        server_mac: [
          {required: true, message: '请输入服务器MAC', trigger: 'blur'},
          {pattern:/^[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}$/i,message: 'MAC地址格式不正确'}
        ],
        server_ip: [
          {required: true, message: '请输入服务器ip', trigger: 'blur'},
          {pattern:/^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/,message: 'IP地址格式不正确'}
        ],
      },
    }
  },
  methods:{
    initData(){
      serverList().then(res=>{
      // axios.get(ip2 + '/server/list/').then(res=>{
        this.serverOptions =[]
        this.serverData = res.data
        this.total = res.data.length
        //手动增加编号
        for (let i =0;i<res.data.length;i++){
          this.serverData[i].id = i + 1
          res.data[i].time = moment(res.data[i].time).format('YYYY-MM-DD HH:mm:ss')
          this.serverOptions.push({
            value:res.data[i].server_id,
            label:(i+1) + ':' + res.data[i].server_name
          })
        }
      })
    },
    addServer(){
      this.serverDialog=true
      this.serveForm.server_ip=''
      this.serveForm.server_name=''
      this.serveForm.server_mac=''
      this.serverMode = '服务器新增'
    },
    editServer(row){
      this.serverMode = '服务器信息修改'
      //JS中的=赋值是赋的地址  所以需要处理一下 不然表单跟表格数据一起变化了
      this.serveForm = JSON.parse(JSON.stringify(row))
      this.serverDialog=true
    },
    //发送新增/修改请求
    addOrEditInfo(serveForm) {
      this.$refs[serveForm].validate((valid) => {
        if (valid) {
          if (this.serverMode === '服务器信息修改'){
            editServer(this.serveForm).then(res=>{
            // axios.post(ip2 + '/server/edit/',this.serveForm).then(res=>{
              if (res.data==='服务器修改成功'){
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.serverDialog = false
                //重新获取数据实现局部刷新
                this.initData()
              }
              else {
                this.$message({
                  message: '修改失败！请检查是否存在字段重复',
                  type: 'warning'
                });
              }
            })
          }
          else {
            addServer(this.serveForm.server_name,this.serveForm.server_mac,this.serveForm.server_ip).then(res=>{
            // axios.post(ip2 + '/server/add/?server_name=' + this.serveForm.server_name +'&server_mac=' + this.serveForm.server_mac + '&server_ip=' + this.serveForm.server_ip).then(res=>{
              if (res.data==='服务器新增成功'){
                this.$message({
                  message: '新增成功',
                  type: 'success'
                });
                this.serverDialog = false
                //重新获取数据实现局部刷新
                this.initData()
              }
              else {
                this.$message.error('新增失败！请检查是否存在字段重复')
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    delServer(row){
      this.$confirm('确定要删除吗？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        delServer(row.server_id).then(res=>{
        // axios.get(this.$ip2 + '/server/del?server_id=' + row.server_id).then(res=>{
          console.log(res);
          if (res.data==='服务器删除成功') {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.initData()
          }
        })
      }).catch(()=>{
        this.$message.info("已取消删除")
      })


    },
    searchServer(){
      searchServer(this.value4).then(res=>{
      // axios.get(ip2 + '/server/get?server_id=' + this.value4).then(res=>{
        console.log(res)
        this.serverData = res.data
        this.serverData[0].id=1
      })
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    showAll(){
      this.initData()
      this.value4 =''
    },
    getCurrentTime() {
      //获取当前时间并打印
      let _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
      // _this.gettime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
      // console.log(this.gettime)
      return yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    },
    serverInfoExport() {
      this.exportVisible = true
    },

    // exportWord(height,width,name,module) {
    //   //这里要引入处理图片的插件，下载docxtemplater后，引入的就在其中了
    //   const _this = this;
    //   //Word路径，在public文件下(CLI3)
    //   JSZipUtils.getBinaryContent(`${module}.docx`, function (error, content) {
    //     if (error) {
    //       throw error
    //     }
    //     let opts = {}
    //     opts.centered = true;
    //     opts.fileType = "docx";
    //     let zip = new PizZip(content);
    //     let doc = new docxtemplater();
    //     doc.loadZip(zip);
    //     // 这里是设置导出的数据
    //     doc.setData({
    //       tableData:_this.tableData, //基础信息
    //       roleData: _this.tableData.roleData
    //       // arr: _this.arr // 评语
    //     })
    //     try {
    //       doc.render()
    //     } catch (error) {
    //       var e = {
    //         message: error.message,
    //         name: error.name,
    //         stack: error.stack,
    //         properties: error.properties,
    //       }
    //       console.log(JSON.stringify({
    //         error: e
    //       }));
    //       throw error;
    //     }
    //     const out = doc.getZip().generate({
    //       type: "blob",
    //       mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    //     })
    //     saveAs(out, `${name}.docx`)
    //   })
    // }
  },
  mounted() {

  },
  created() {
    this.initData()
  }
}
</script>

<style scoped>
</style>
